
/*
 * @Description: 操作cookie的方法
 * @Date: 2021-09-05 10:16:49
 * @LastEditTime: 2021-09-21 15:53:09
 * @FilePath: \vue-h5\src\utils\user.js
 */
import Cookies from 'js-cookie'

// cookie保存的天数
const cookieExpires = 30
export const TOKEN_KEY = 'token'
export const USER_INFO = 'userInfo'
export const USER_KEY = 'userId' // 账号

// 保存token
export const setToken = (token) => {
  Cookies.set(TOKEN_KEY, token, { expires: cookieExpires || 1 })
}

// 获取token
export const getToken = () => {
  const token = Cookies.get(TOKEN_KEY)
  if (token) return token
  else return ''
}

// 删除token
export const removeToken = () => {
  Cookies.remove(TOKEN_KEY)
  const token = Cookies.get(TOKEN_KEY)
  if (!token) return ''
}

// 保存用户的数据
export const setUserInfo = (data) => {
  if (data === undefined || typeof (data) === 'undefined') {
    return
  }
  Cookies.set(USER_INFO, data, { expires: cookieExpires || 1 })
}

// 获取用户的数据
export const getUserInfo = () => {
  const userData = Cookies.getJSON(USER_INFO)
  if (userData) return userData
  else return ''
}

// 删除用户的数据
export const removeUserInfo = () => {
  Cookies.remove(USER_INFO)
  const userData = Cookies.get(USER_INFO)
  if (!userData) return ''
}

// 保存用户id
export const setUserId = (userId) => {
  if (userId === undefined || typeof (userId) === 'undefined') {
    return
  }
  // sessionStorage.setItem(USER_KEY, userId);
  // window.localStorage.setItem(USER_KEY, userId);
  console.log('userId', userId)
  Cookies.set(USER_KEY, userId, { expires: cookieExpires || 1 })
}

// 获取用户id
export const getUserId = () => {
  const userId = Cookies.get(USER_KEY)
  if (userId) return userId
  else return false
}
